package com.bt.lms.ui.page.sys.study.action;

import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.SysBizTypeConstant;
import com.bt.lms.entity.StudyCen;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.sys.study.PageAdd;
import com.bt.lms.ui.page.sys.study.PageCompile;
import com.bt.lms.ui.page.sys.utils.ArrayUtils;
import com.bt.lms.ui.page.sys.utils.NetWorkUtils;
import com.bt.lms.ui.vo.PageSkipInfo;
import com.bt.lms.ui.page.sys.ServerInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.page.sys.utils.Encode;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

/**
 * 保存按钮事件（编辑学习中心界面）
 *
 * @author 徐大永
 */
public class SCSaveBtn implements EventHandler<ActionEvent> {

    /**
     * 界面跳转信息
     */
    private final PageSkipInfo pageSkipInfo;

    /**
     * 源学习中心信息
     */
    private final StudyCen studyCen;

    /**
     * 构建事件
     *
     * @param pageSkipInfo 界面跳转信息
     * @param studyCen 源学习中心信息
     */
    public SCSaveBtn(PageSkipInfo pageSkipInfo, StudyCen studyCen) {
        this.pageSkipInfo = pageSkipInfo;
        this.studyCen = studyCen;
    }

    /**
     * 方法实现
     *
     * @param event the event which occurred
     */
    @Override
    public void handle(ActionEvent event) {

        //1.获取用户输入
        StudyCen studyCen = getInPut();
        //2.验证用户输入
        String hint = verifyInPut(studyCen);
        //3.组装网络消息包
        if (hint == null) {
            ReqMsg reqMsg = Encode.encodeToMsg(studyCen, SysBizTypeConstant.STUDY_CEN_COMPILE);
            byte[] bytes = reqMsg.toBytes();
            //4.组网
            Socket socket = packageNet();
            OutputStream out;
            try {
                out = socket.getOutputStream();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //5.发送
            boolean b = sendMes(out, bytes);
            if (b)
                //接受响应
                //判断是否发送成功
                try {
                    //3.2 接收响应
                    InputStream in = socket.getInputStream();
                    //3.2.1 接受响应
                    List<byte[]> bufS = NetWorkUtils.receive(in);
                    //3.2.2 处理结果
                    byte[] respBytes = ArrayUtils.joinBytes(bufS);
                    //3.2.3 转消息
                    RespMsg respMsg = RespMsg.toRespMsg(respBytes);
                    //3.2.4 比较状态
                    short status = respMsg.getStatus();
                    if (status == RespMsg.NETWORK_STATUS_NORMAL) {
                        //关流
                        in.close();
                        out.close();
                        socket.close();
                        //成功发送，程序结束
                        finish();
                    } else {
                        String failStr = "未能保存成功，请稍候重试。";
                        hintFrame(failStr);//提示框
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            else{
                //非正常结束
                hintFrame("保存失败，请稍候重试");//提示框
            }
        } else {
            hintFrame(hint);//提示框
        }
    }

    /**
     * 获取用户输入
     *
     * @return 学习中心
     */
    private StudyCen getInPut() {

        StudyCen studyCen = new StudyCen();
        //维护无需用户输入的属性
        studyCen.setId(this.studyCen.getId());
        studyCen.setCode(this.studyCen.getCode());
        //界面
        Pane pane = pageSkipInfo.getPane();
        //名称
        TextField nameTF = (TextField) pane.lookup("#" + PageCompile.NAME_FT);
        String name = nameTF.getText().trim();
        studyCen.setName(name);
        //所在地
        ComboBox<String> oneCB = (ComboBox<String>)pane.lookup("#" + PageAdd.LOCATION_ONE);
        String provinceStr = oneCB.getValue();
        ComboBox<String> twoCB = (ComboBox<String>)pane.lookup("#" + PageAdd.LOCATION_TWO);
        String regionStr = twoCB.getValue();
        ComboBox<String> threeCB = (ComboBox<String>)pane.lookup("#" + PageAdd.LOCATION_THREE);
        String cityStr = threeCB.getValue();
        studyCen.setAddress(provinceStr + regionStr + cityStr);
        //联系人
        TextField relationTF = (TextField) pane.lookup("#" + PageCompile.RELATION_TD);
        String relation = relationTF.getText().trim();
        studyCen.setRelationPen(relation);
        //移动电话
        TextField phoneTF = (TextField) pane.lookup("#" + PageCompile.PHONE_TF);
        String phone = phoneTF.getText().trim();
        studyCen.setPhone(phone);
        //电子邮箱
        TextField emailTF = (TextField) pane.lookup("#" + PageCompile.EMAIL_TF);
        String email = emailTF.getText().trim();
        studyCen.setEmail(email);
        //学习中心描述
        TextArea describeTA = (TextArea) pane.lookup("#" + PageCompile.DESCRIBE_TA);
        String describe = describeTA.getText();
        if (describe == null){
            studyCen.setDescribe(null);
        }else
            studyCen.setDescribe(describe.trim());

        return studyCen;
    }

    /**
     * 验证用户输入
     *
     * @param studyCen 用户输入
     * @return 验证结果
     */
    private String verifyInPut(StudyCen studyCen) {

        //提示信息
        String hint = "";

        //1.学习中心名称 必填，文本  8字符以下
        String name = studyCen.getName();
        int nameLen = name.length();
        if ("".equals(name)) {
            hint += "请输入学习中心的名字。\n";
        } else if (nameLen > 15) {
            hint += "名字长度不合适，请输入8位以下的名称。\n";
        }

        //2.联系人 必填 文本 32位以下
        String relation = studyCen.getRelationPen();
        int codingLen = relation.length();

        if ("".equals(name)) {
            hint += "请输入学习中心的联系人。\n";
        } else if (codingLen > 32) {
            hint += "联系人过长，请不要超过32位。\n";
        }

        //3.移动电话 必填 文本 11位
        String phone = studyCen.getPhone();
        int phoneLen = phone.length();

        if ("".equals(name)) {
            hint += "请输入联系人的联系方式。\n";
        } else if (phoneLen > 11) {
            hint += "联系方式过长，请不要大于11位。\n";
        }

        //4.电子邮箱 必填 文本 64以下
        String email = studyCen.getEmail();
        int emailLen = email.length();
        if ("".equals(name)) {
            hint += "请输入联系人的电子邮箱。\n";
        } else if (emailLen > 64) {
            hint += "电子邮箱太长，请不要大于64位。\n";
        }

        //5.学习中心描述 非必填 文本 255以下
        String describe = studyCen.getDescribe();
        if (describe != null){
            int describeLen = describe.length();
            if (!"".equals(describe)) {
                if (describeLen > 255) {
                    hint += "学习中心描述太长，最大255。\n";
                }
            }
        }

        return "".equals(hint) ? null : hint;
    }

    /**
     * 组网
     *
     * @return 网
     */
    private Socket packageNet() {

        String ip = ServerInfo.IP;
        Integer port = ServerInfo.PORT;

        try {
            return new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送消息
     *
     * @param out   输出流
     * @param bytes 要发送的byte数组
     * @return 发送结果
     */
    private boolean sendMes(OutputStream out, byte[] bytes) {

        try {
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 失败提示框
     *
     * @param hint 提示内容
     */
    private void hintFrame(String hint) {
        //失败提示
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("失败");
        alert.setHeaderText(null);
        alert.setContentText(hint);
        alert.showAndWait();
    }

    /**
     * 结束方法（弹窗 + 界面跳转）
     */
    private void finish() {
        //保存提示
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("成功");//头部提示
        alert.setHeaderText(null);//清除固有提示
        alert.setContentText("保存成功");//提示文本
        alert.showAndWait();//显示

        //界面跳转
        NetWorkUtils.reqStudyCenPagingPage(pageSkipInfo, new Page<>());
    }
}
